package com.example.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.common.Result;
import com.example.entity.Admin;
import com.example.service.AdminService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Resource
    private AdminService adminService;

    @GetMapping("/selectAll")
    public Result selectAll(Admin admin) {
        List<Admin> adminList = adminService.selectAll(admin);
        return Result.success(adminList);
    }

    @PostMapping("/add")
    public Result add(@RequestBody Admin admin) {   //@RequestBody 接收前端传来的json，post、put、delete可用，get不能用
        adminService.add(admin);
        return Result.success();
    }

    @PutMapping("/update")
    public Result update(@RequestBody Admin admin) {   //@RequestBody 接收前端传来的json，post、put、delete可用，get不能用
        adminService.update(admin);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {  //@PathVariable 接收前端传来的路径参数
        adminService.deleteById(id);
        return Result.success();
    }

    @DeleteMapping("/deleteBatch")
    public Result delete(@RequestBody List<Admin> list) {  //@PathVariable 接收前端传来的路径参数
        adminService.deleteBatch(list);
        return Result.success();
    }

    @GetMapping("/selectPage")
    public Result selectPage(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             Admin admin) {
        PageInfo<Admin> pageInfo = adminService.selectPage(pageNum, pageSize, admin);
        System.out.println("分页结果：" + pageInfo); // 调试日志
        return Result.success(pageInfo);
    }

    //excel导出
    @GetMapping("/export")
    public void exportData(Admin admin, HttpServletResponse response) throws Exception {
        System.out.println("前端传入 idsStr: " + admin.getIds()); // 查看是否接收到参数
        System.out.println("转换后 idsArr: " + Arrays.toString(admin.getIdsArr()));
        String ids = admin.getIds();
        if (StrUtil.isNotBlank(ids)) {
            String[] idsArr = ids.split(",");
            admin.setIdsArr(idsArr);
        }
        //先获取所有数据
        List<Admin> adminList = adminService.selectAll(admin);
        //getWriter()默认创建xls格式的excel文件，使用getWriter(true)创建xlsx格式文件
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("username", "账号");
        writer.addHeaderAlias("name", "昵称");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("email", "邮箱");
        // 默认的，未添加alias的属性也会写出，如果想只写出加了别名的字段，可以调用此方法排除之
        writer.setOnlyAlias(true);
        // 合并单元格后的标题行，使用默认标题样式
        //writer.merge(3, "校园交友论坛用户信息");
        //写出数据
        writer.write(adminList,true);
        //导出为xlxs文件,response为HttpServletResponse对象
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String filename = URLEncoder.encode("校园交友论坛用户信息", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition","attachment;filename=" + filename + ".xlsx");
        ServletOutputStream out=response.getOutputStream();
        writer.flush(out, true);
        //关闭writer，释放内存
        writer.close();
        IoUtil.close(out);
    }

    /**
     * 批量导入
     */
    @PostMapping("/import")
    public Result importData(MultipartFile file) throws Exception {
        //  1. 拿到输入流 构建 reader
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //  2. 通过Reader 读取 excel 里面的数据
        reader.addHeaderAlias("账号", "username");
        reader.addHeaderAlias("昵称", "name");
        reader.addHeaderAlias("电话", "phone");
        reader.addHeaderAlias("邮箱", "email");
        List<Admin> list = reader.readAll(Admin.class);
        // 3. 将数据写到数据库
        for (Admin admin : list) {
            adminService.add(admin);
        }
        return Result.success();
    }
}
